package one.stand.service.impl;

import com.alibaba.fastjson.JSONObject;
import one.stand.model.ResultModel;
import one.stand.model.SunCodeModel;
import one.stand.request.SunCodeRequest;
import one.stand.service.WxMessageService;
import one.stand.service.WxSunCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

/**
 * @author: QIK
 * @CreateDate: 2019/4/29 11:32
 */
@Service
public class WxSunCodeServiceImpl extends PublicBaseService implements WxSunCodeService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String getWxCode(JSONObject paramJson, String accessToken) {
        try {
            SunCodeModel model = new SunCodeModel();
            model.setPage(paramJson.getString("page"));
            model.setScene(paramJson.getString("scene"));
            model.setCreateTime(currentDate());


            SunCodeModel outModel  = sunCodeMapper.select(model);
            if(null!=outModel){
                if(!StringUtils.isBlank(outModel.getUrl())){
                    return outModel.getUrl();
                }
            }
            int insert=  sunCodeMapper.insertSelective(model);
            if(insert<=0){
                log.info("生成太阳码失败:参数存储错误");
                return null;
            }
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> requestEntity = new HttpEntity(paramJson, headers);
            ResponseEntity<byte[]> entity = restTemplate.exchange(wxUrlConfig.getWxCodeUrl() + accessToken, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            byte[] result = entity.getBody();
            InputStream inputStream = new ByteArrayInputStream(result);
            String filename = System.currentTimeMillis() + ".png";
            String url=ossUtil.getOssUrl() +ossUtil.uploadObjectOSS(new File(filename), inputStream);
            model.setUrl(url);
            sunCodeMapper.updateByPrimaryKeySelective(model);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Autowired
    WxMessageService wxMessageService;
    @Override
    public String getWxCode(JSONObject paramJson, String appid,String appSecret) {
        try {
         String accessToken=   wxMessageService.getWxToken(appid,appSecret);
            return getWxCode(paramJson,accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
